import { isEmpty } from "lodash-es";
import create from "zustand";
import { devtools, persist } from "zustand/middleware";

import { STORAGE_NAMES } from "~/modules/storage/storage-names";

export interface TokenState {
  token?: string;
}

export interface TokenActions {
  setToken: (token: string) => void;
  hasToken: () => boolean;
  cleanToken: () => void;
}

const initState = (): TokenState => {
  return {
    token: undefined,
  };
};

export const useTokenStore = create<TokenState & TokenActions>(
  // @ts-ignore
  devtools(
    persist(
      (set, get, api) => ({
        ...initState(),
        setToken: (token: string) => {
          set({ token });
        },
        cleanToken: () => {
          set({ token: undefined });
        },
        hasToken: () => {
          return !isEmpty(get().token);
        },
      }),
      {
        name: STORAGE_NAMES.TOKEN.name,
        version: STORAGE_NAMES.TOKEN.version,
      }
    )
  )
);
